/* global window */
import modelExtend from 'dva-model-extend'
import { config } from 'utils'
import { message } from 'antd'
import { getCurrentUser, update } from 'services/sysUser'
import { pageModel } from '../common'

export default modelExtend(pageModel, {
  namespace: 'sysUserDetail',

  state: {
    data: {},
  },

  subscriptions: {
    setup ({ dispatch, history }) {
      history.listen((location) => {
        if (location.pathname === '/sysUser/detail') {
          dispatch({
            type: 'query',
          })
        }
      })
    },
  },

  effects: {

    * query ({ payload = {} }, { call, put }) {
      const data = yield call(getCurrentUser)
      if (data.success) {
        yield put({
          type: 'updateState',
          payload: {
            editType: 'update',
            data: data.data,
          },
        })
      } else {
        throw data
      }
    },


    * update ({ payload }, { select, call, put }) {
      const id = yield select(({ sysUserDetail }) => sysUserDetail.data.id)
      const newData = { ...payload, id }
      const data = yield call(update, newData)
      if (data.success) {
        message.success('update success')
        yield put({ type: 'query' })
      } else {
        message.error('update failed')
        throw data
      }
    },

  },

  reducers: {

  },
})
